﻿using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Threading;
using DataStore;
using DataStore.Domain;
using DataStore.Repositories;
using Infrastructure.CurrentData;
using Microsoft.Practices.Composite.Events;

namespace Infrastructure.ViewModels
{
    /// <summary>
    /// AllAuthors viewmodel
    /// </summary>
    public class AllAuthorsViewModel : DataModel
    {
        readonly ObservableCollection<AuthorViewModel> _authors = new ObservableCollection<AuthorViewModel>();

        /// <summary>
        /// Initializes a new instance of the <see cref="AllAuthorsViewModel"/> class.
        /// </summary>
        public AllAuthorsViewModel() : base()
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AllAuthorsViewModel"/> class.
        /// </summary>
        /// <param name="eventAggregator">The event aggregator.</param>
        public AllAuthorsViewModel(IEventAggregator eventAggregator) : base(eventAggregator)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        void Initialize()
        {
            RefreshAuthors();
        }

        /// <summary>
        /// Refreshes the authors.
        /// </summary>
        public void RefreshAuthors()
        {
            if (!ThreadPool.QueueUserWorkItem(FetchAuthorsCallback))
            {
                State = ModelState.Invalid;
            }
        }

        /// <summary>
        /// Fetches the authors callback.
        /// </summary>
        /// <param name="state">The state.</param>
        private void FetchAuthorsCallback(object state)
        {
            IDatabase database = Current.Container.Resolve<IDatabase>();
            var unitOfWork = database.CreateUnitOfWork();

            try
            {
                IRepository<Author> repository = new AuthorRepository(unitOfWork);
                var authors = repository.All;

                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            _authors.Clear();
                                            foreach (Author author in authors)
                                            {
                                                _authors.Add(new AuthorViewModel(EventAggregator, author));
                                            }
                                            unitOfWork.Dispose();
                                            State = ModelState.Active;
                                        }),
                    DispatcherPriority.ApplicationIdle);
            }
            catch (Exception e)
            {
                Log.Error("Failed to load Authors", e);

                unitOfWork.Dispose();
                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            State = ModelState.Invalid;
                                        }),
                    DispatcherPriority.ApplicationIdle);

            }
        }

        /// <summary>
        /// Gets the authors.
        /// </summary>
        /// <value>The authors.</value>
        public  ObservableCollection<AuthorViewModel> Authors
        {
            get
            {
                VerifyCalledOnUIThread();
                return _authors;
            }
        }
    }
}